package Filter;

import DataBase.DataBase;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class HistoryFilter implements Filter {

    private FilterConfig filterConfig =null;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //获取ServletContext对象，用于记录日志
        ServletContext context=this.filterConfig.getServletContext();
        //将请求转换成HttpServletRequest请求
        HttpServletRequest req =(HttpServletRequest) servletRequest;
        //存入日志中
        String LogInfo = req.getServletPath();
        if(req.getSession().getAttribute("username") != null){
            if(req.getQueryString()!=null) LogInfo = LogInfo + "?" +req.getQueryString();
            String username = req.getSession().getAttribute("username").toString();
            DataBase.setLogInfo(username,LogInfo);
        }
        //链式处理，放行到目的地址
        filterChain.doFilter(servletRequest,servletResponse);

    }

    @Override
    public void destroy() {
        filterConfig = null;
    }
}
